<template>
    <div class="file-button" v-if="store.state.showButton===false" >
        <el-upload
            :file-list="uploadList"
            multiple
            :show-file-list="false"
            :http-request="customRequest"
        >
            <el-button type="primary" >上传</el-button>
        </el-upload>
        <UploadFloderBtn/>
        <NewFloderBtn/>
    </div>
    <div class="file-button" v-if="store.state.showButton===true">
        <DownloadBtn/>
        <DeleteBtn/>
        <RecoverBtn v-if="allStore.state.currentMenu==='回收站'" />
        <RenameBtn/>
    </div>
</template>

<script setup lang="ts">
import UploadFloderBtn from '@/components/disk/button/UploadFloderBtn.vue'
import NewFloderBtn from '@/components/disk/button/NewFloderBtn.vue'
import DownloadBtn from '@/components/disk/button/DownloadBtn.vue'
import DeleteBtn from '@/components/disk/button/DeleteBtn.vue'
import RecoverBtn from '@/components/disk/button/RecoverBtn.vue'
import RenameBtn from '@/components/disk/button/RenameBtn.vue'
import { computed } from 'vue'
import { ElMessage} from 'element-plus'
import { fileStore} from '@/stores/disk/file'
import {useAllDataStore} from '@/stores/index'
import { uploadSmallFile,uploadChunk,mergeChunks} from '@/api/disk/file'
const store= fileStore();
const allStore = useAllDataStore();
/**
 * 上传文件
 */
const uploadList = computed(() => {
  return store.state.uploadList
})
//上传
const customRequest = async (options:any) => {
  const smallFileThreshold = 20 * 1024 * 1024; 
  const {file} = options;
  console.log('customRequest',file);  
  //打开弹窗
  store.updateShowPopup(true)
  //添加到上传列表
  store.addToUploadList(file,file.uid)
  let relativePath = null;
  if (file.webkitRelativePath) {
    relativePath = file.webkitRelativePath;
  } else {
    relativePath = file.name;
  }
  //判断文件是否超过限制
  if (file.size < smallFileThreshold) {
    console.log('小文件上传');
    const fileMD5 = await store.calculateMD5(file);
    const formData = new FormData();
    formData.append('fileName', file.name)
    formData.append('fileMD5', fileMD5); 
    formData.append('chunk', file);
    formData.append('relativePath', relativePath);
    try {
      await uploadSmallFile(formData,file)
    } catch (error) {
      console.log('上传失败',error);
      ElMessage.error('小文件上传失败');
    }
  } else {
    console.log('大文件上传');
    // 大文件分片上传
    const chunkSize = 1024 * 1024 * 5;
    const fileMD5 = await store.calculateMD5(file);
    //1.切割文件为分片
    const chunks = store.sliceFile(file,chunkSize)
    let uploadedChunks = 0; // 已上传分片数
    const totalChunks = chunks.length;//总分片数
    //2.循环上传分片
    var isNotuploaded =0; //是否秒传完成
    for (let i = 0; i < chunks.length; i++) {
      const chunkIndex = i;//分片索引
      const chunk = chunks[i];
      //3.发送分片请求
      const formData = new FormData();
      formData.append('fileName', file.name);
      formData.append('chunk', chunk);
      formData.append('chunkIndex', chunkIndex);
      formData.append('totalChunks', totalChunks);
      formData.append('fileMD5', fileMD5); 
      formData.append('relativePath', relativePath);
      try {
        const res = await uploadChunk(formData,file);
        uploadedChunks++;
        if (res.data === 1) {
          //跳出循环
          isNotuploaded=1;
          break;
        }
      } catch (error) {
        console.log('上传失败',error);
         //TODO 这里可以添加重试机制
         // 例如：return retryUploadChunk(formData, options, retries);
      }
    }
    //判断是否秒传成功
    if(isNotuploaded===1){
      store.updateUploadProgress(file.uid, 100)
      return;
    }
    
    //4.发送合并分片请求  
    try {
      store.updateUploadProgress(file.uid, 92)
      if (uploadedChunks === totalChunks) {
        const mergeFormData = new FormData();
        mergeFormData.append('fileName', file.name);
        mergeFormData.append('fileMD5', fileMD5);
        mergeFormData.append('totalChunks', totalChunks);
        mergeFormData.append('fileSize', file.size);
        mergeFormData.append('relativePath', relativePath);
        await mergeChunks(mergeFormData, file);
      } else {
        console.log('部分分片上传失败');
      }
    } catch (error) {
      console.log('合并分片请求失败', error);
      ElMessage.error(`大文件上传失败`);
    }
  }
  //清楚面包屑
  store.updateCurrentBread(null)
  //重新请求数据
  store.initFileList()
  
};
// 上传重试机制示例函数（可选）
function retryUploadChunk(formData, options, retries = 3) {
  return new Promise((resolve, reject) => {
    let attempt = 0;

    const upload = () => {
      uploadChunk(formData, options)
        .then(resolve)
        .catch(error => {
          attempt++;
          if (attempt < retries) {
            console.log(`重试上传分片（尝试 ${attempt}）`);
            upload();
          } else {
            reject(error);
          }
        });
    };

    upload();
  });
}





</script>

<style scoped>
.file-button{
    display: flex;
}
.file-button > * {
    margin-right: 10px; /* 给每个子元素的右侧添加 20px 的外边距 */
}
</style>